<?php
/**
 * Description: 用户合并
 * User: devforma
 * Date: 2016/10/25
 * Time: 16:40
 */

class MergeUser implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $uddb;

        if (empty($queryArgs['source_user_id']) || empty($queryArgs['source_user_token'])
            || empty($queryArgs['target_user_id']) || empty($queryArgs['target_user_token']) || $queryArgs['source_user_id'] == $queryArgs['target_user_id']) {
            return genOutput(1000);
        }

        $sql = 'SELECT * FROM `user_auth_info` WHERE `ID`=:uid AND `user_token`=:token';
        $sourceUser = $uddb->getRow($sql, [':uid' => $queryArgs['source_user_id'], ':token' => $queryArgs['source_user_token']]);
        $targetUser = $uddb->getRow($sql, [':uid' => $queryArgs['target_user_id'], ':token' => $queryArgs['target_user_token']]);

        if ($sourceUser && $targetUser && $this->merge($sourceUser, $targetUser)) {

            $allMergedUser = $uddb->getCol('SELECT `ID` FROM `user_auth_info` WHERE `merged_to`!=0'); //获取所有的已经被merge掉的用户id

            $cacheKey = 'allMergedUser';
            cacheSet($cacheKey, $allMergedUser, 30*24*60*60);

            return genOutput(1);
        }

        return genOutput(1001);
    }

    /**
     * 合并用户
     *
     * @param $firstUser
     * @param $secondUser
     * @return bool
     */
    private function merge($firstUser, $secondUser) {
        global $uddb, $cmsdb;

        $firstUserId = $firstUser->ID;
        $secondUserId = $secondUser->ID;

        $oldUser = array(
            'user_email'    => '0',
            'user_pass'     => '',
            'phone'         => null,
            'weibo'         => '0',
            'weixin'        => '0',
            'related_phone' => '0',
            'merged_to'     => $secondUserId
        );

        $newUser = array(
            'user_email'    => !empty($secondUser->user_email) ? $secondUser->user_email : $firstUser->user_email,
            'user_pass'     => !empty($secondUser->user_pass) ? $secondUser->user_pass : $firstUser->user_pass,
            'weibo'         => !empty($secondUser->weibo) ? $secondUser->weibo : $firstUser->weibo,
            'weixin'        => !empty($secondUser->weixin) ? $secondUser->weixin : $firstUser->weixin,
            'related_phone' => !empty($secondUser->related_phone) ? $secondUser->related_phone : $firstUser->related_phone,
        );

        $newPhone = !empty($secondUser->phone) ? $secondUser->phone : $firstUser->phone;
        if ($newPhone)
            $newUser['phone'] = $newPhone;

        //更新用户表
        $uddb->beginTransaction();
        $r2 = $uddb->update('user_auth_info', $oldUser, array('ID' => $firstUserId)); //更新待抹掉的账号信息
        $r1 = $uddb->update('user_auth_info', $newUser, array('ID' => $secondUserId)); //更新待保留的账号信息

        if ($r1 !== false && $r2 !== false) {

            //更新订单及商品关联
            $cmsdb->beginTransaction();
            $r3  = $cmsdb->update('relation_user_product', array('user_id' => $secondUserId), array('user_id' => $firstUserId));
            $r4  = $cmsdb->update('original_orders', array('user_id' => $secondUserId), array('user_id' => $firstUserId));
            $r5  = $cmsdb->update('express_tasks', array('user_id' => $secondUserId), array('user_id' => $firstUserId));
            $r6  = $cmsdb->update('refund_orders', array('user_id' => $secondUserId), array('user_id' => $firstUserId));
            $r7  = $cmsdb->update('withdraw_records', array('user_id' => $secondUserId), array('user_id' => $firstUserId));

            if ($r3 !== false && $r4 !== false && $r5 !== false && $r6 !== false && $r7 !== false) {
                $cmsdb->endTransaction();
                $uddb->endTransaction();

                cacheDelete('userInfo:'.$firstUserId);
                cacheDelete('userInfo:'.$secondUserId);

                return true;

            } else {
                $cmsdb->cancelTransaction();
                $uddb->cancelTransaction();
            }

        } else {
            $uddb->cancelTransaction();
        }

        return false;
    }
}